<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>样式简写</title>
    <style>
      .b1 {
        width: 100px;
        height: 100px;
        background-color: yellowgreen;
      }

      .b2 {
        width: 200px;
        height: 200px;
        background-color: red;
      }
    </style>
  </head>
  <body>
    <button id="btn">点我变化</button>
    <br /><br />
    <div id="box" class="b1"></div>

    <script>
      var box = document.getElementById("box");
      var btn = document.getElementById("btn");

      btn.onclick = function () {
        // addClass(box, "b2");
        removeClass(box, "b1");
      };

      function addClass(obj, className) {
        if (!hasClass(obj, className)) {
          obj.className += " " + className;
        }
      }

      function hasClass(obj, className) {
        var reg = new RegExp("\\b" + className + "\\b");
        return reg.test(obj.className);
      }

      function removeClass(obj, className) {
        var reg = new RegExp("\\b" + className + "\\b");
        if (hasClass(obj, className)) {
          obj.className = obj.className.replace(reg, "");
        }
      }
    </script>
  </body>
</html>
